package org.bright.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.bright.dto.OrderItemDTO;
import org.bright.entity.*;
import org.bright.mapper.PurchaseOrdersMapper;
import org.bright.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.bright.util.OrderIdGenerator;
import org.bright.vo.ProductsDisplayVO;
import org.bright.vo.PurchaseOrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购订单表 记录采购订单信息 服务实现类
 * </p>
 *
 * @author bright
 * @since 2024-10-21
 */
@Service
public class PurchaseOrdersServiceImpl extends ServiceImpl<PurchaseOrdersMapper, PurchaseOrders> implements IPurchaseOrdersService {
    @Autowired
    private IProductsService productsService;
    @Autowired
    private PurchaseOrdersMapper purchaseOrdersMapper;
    @Autowired
    private IPurchaseOrderDetailsService purchaseOrderDetailsService;
    @Autowired
    private IPurchaseSettlementService purchaseSettlementService;
    @Autowired
    private IInventoryService iInventoryService;
    @Override
    @Transactional
    public int createOrders(List<OrderItemDTO> orderItems) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        //        订单id
        String orderId = OrderIdGenerator.generateOrderId();
        // 获取商品Id集合
        List<Integer> productIds = orderItems.stream().map(OrderItemDTO::getProductId).collect(Collectors.toList()); // 先拿出所有的商品id
        // 根据商品id查询商品信息
        List<ProductsDisplayVO> productList = productsService.getListByProductId(productIds);
        Map<Integer, Integer> map = orderItems.stream().
                collect(
                        Collectors.toMap(
                                OrderItemDTO::getProductId,
                                OrderItemDTO::getQuantity)
                );
        //商品根据供应商Id就行分组
        Map<Integer, List<ProductsDisplayVO>> groupedBySupplierId = productList.stream()
                .collect(Collectors.groupingBy(ProductsDisplayVO::getSupplierId));
        List<PurchaseOrders>  purchaseOrdersList = new ArrayList<>();
        groupedBySupplierId.forEach((supplierId, items) -> {
//            podId.set(items.size());
            System.out.println("supplierId ID: " + supplierId);
            //创建子订单
            PurchaseOrders purchaseOrders = new PurchaseOrders();
            purchaseOrders.setOrderId(orderId);
            purchaseOrders.setSupplierId(supplierId);
//        日期
            purchaseOrders.setOrderDate(new Date());
            // 0未发货  1已发货 2发货中 3已收货、
//        状态
            purchaseOrders.setStatus(0);
            double total = items.stream().mapToDouble(item -> map.get(item.getProductId()) * item.getPurchasePrice()).sum();
            purchaseOrders.setTotalAmount(total);
//           放入到List里面
            purchaseOrdersList.add(purchaseOrders);
        });

        // 合成订单详情的商品项
        List<PurchaseOrderDetails> purchaseOrderDetails = productList.stream().filter(
                item -> map.containsKey(item.getProductId())).map(
                item -> new PurchaseOrderDetails(
                        orderId,
                        item.getProductId(),
                        map.get(item.getProductId()),
                        item.getPurchasePrice(),
                        item.getSupplierId(),
                        map.get(item.getProductId()) * item.getPurchasePrice()
                )
        ).collect(Collectors.toList());
        //保存到数据库
        int i = purchaseOrdersMapper.insertBatch(purchaseOrdersList);
        purchaseOrderDetailsService.insertIntoOrderDetails(purchaseOrderDetails);
        return 1;
    }

    @Override
    public PageInfo<PurchaseOrderVO> selectAll(Integer pageNum) {
        PageHelper.startPage(pageNum,4);
        List<PurchaseOrderVO> purchaseOrderVOS = purchaseOrdersMapper.selectAll();
        purchaseOrderVOS.forEach(item->
                //获取该订单的子订单
                item.setOrderItems(purchaseOrdersMapper.selectAllByOrderId(item.getOrderId()))
                );
        PageInfo<PurchaseOrderVO> pageInfo = new PageInfo<>(purchaseOrderVOS);
        return pageInfo;
    }

    @Override
    public List<PurchaseOrderVO> selectAllByOrderId(String orderId) {
        return purchaseOrdersMapper.selectAllByOrderId(orderId);
    }
//把某大订单的子订单的状态改为已发货，如果所有的子订单都已发货，那么修改所有该订单的状态为2变成已发货状态
    @Override
    public int updateStatus(String orderId, int supplierId) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        int num = purchaseOrdersMapper.updateStatus(orderId,supplierId,1);
        //获取全部订单
        List<PurchaseOrderVO> purchaseOrderVOS = purchaseOrdersMapper.selectAllByOrderId(orderId);
        boolean allStatusOne = purchaseOrderVOS.stream().allMatch(order -> order.getStatus() == 1);
        if(allStatusOne){
            CustomRobotGroupMessage.getSign("您有订单待收货");
            return purchaseOrdersMapper.updateStatusByOrderId(orderId,2);
        }
        return num;
    }
//修改总订单状态，也就是收货
//    收货的时候增加库存
    @Override
    public int updateStatusByOrderId(String orderId) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        List<PurchaseOrderVO> purchaseOrderVOS = purchaseOrdersMapper.selectAllByOrderId(orderId);
        purchaseOrderVOS.forEach(item->{
            PurchaseSettlement purchaseSettlement = new PurchaseSettlement();
            purchaseSettlement.setPoId(item.getOrderId());
            purchaseSettlement.setTotalAmount(Double.valueOf(item.getTotalPrice()));
            purchaseSettlement.setSupplierId(item.getSupplierId());
            purchaseSettlement.setShipment(new Date());
            purchaseSettlement.setSettlementStatus(0);
            purchaseSettlementService.insertInto(purchaseSettlement);
        });
        List<PurchaseOrderDetails> purchaseOrderDetails = purchaseOrderDetailsService.selectProductIdFromOrderId(orderId);
        purchaseOrderDetails.forEach(item->{
            Inventory inventory = iInventoryService.selectAllByProductId(item.getProductId());
            if(inventory!=null){
                iInventoryService.updateQuantityAndCreatedTime(inventory.getQuantity() + item.getQuantity(), item.getProductId());
            }else {
                iInventoryService.insertQuantityAndCreatedTime(item.getQuantity(), item.getProductId());
            }
        });
        int i = purchaseOrdersMapper.updateStatusByOrderId(orderId, 3);
        CustomRobotGroupMessage.getSign("您有新的订单未结算！");
        return i;
    }
}
